package classconverstation.cscl.ist.psu.edu.client;

import java.util.ArrayList;

import classconverstation.cscl.ist.psu.edu.client.messengers.Course;
import classconverstation.cscl.ist.psu.edu.client.messengers.User;
import classconverstation.cscl.ist.psu.edu.client.services.LoginService;
import classconverstation.cscl.ist.psu.edu.client.services.LoginServiceAsync;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CaptionPanel;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class CCProfile implements EntryPoint {
    String user_id = null;
    
    /* Commenting out these because this may make the browser frozen
    Timer timer = new Timer() {
        public void run() {
            if (user_id == null) {
                getUserOpenID();
            }
            else {
                if (user_id.trim().length() > 0) {
                    this.cancel();
                }
            }
        }
    };
    */
    
    
    TextBox open_id;
    
	private LoginServiceAsync loginServiceSvc = GWT.create(LoginService.class);
	
	public void onModuleLoad() {
		getUserOpenID();
	    //timer.scheduleRepeating(3000);
        RootPanel rootPanel = RootPanel.get();
        
        rootPanel.add(new HTML("<H2>Welcome to the class covnersation!</H2><pYou see this page, because you are the first time visit us with the OpenId you just provided.</p>"));
        rootPanel.add(new HTML("<p>For grading purpose, the first time when you use your open ID login, the system will ask you to provide your PSU id (i.e., abc123) and your name to create a short profile.</p>"));
        rootPanel.add(new HTML("<p>Please notice that upon creating the profile, an email containing a confirmation link will be sent to your psu webmail (i.e.,abc123@psu.edu). This action is to prevent somebody making wrong purposeful connection to your psu credential.</p>"));
        
        CaptionPanel cptnpnlNewPanel = new CaptionPanel("User Basic Info");
        rootPanel.add(cptnpnlNewPanel, 45, 100);
        cptnpnlNewPanel.setSize("650px", "168px");
        
        Grid grid = new Grid(5, 3);
        cptnpnlNewPanel.setContentWidget(grid);
        grid.setSize("653px", "145px");
        
        Label lblOpenid = new Label("OpenID");
        grid.setWidget(0, 0, lblOpenid);
        lblOpenid.setWidth("116px");
        
        open_id = new TextBox();
        open_id.setText("loading....");
        
        open_id.setEnabled(false);
        grid.setWidget(0, 1, open_id);
        open_id.setWidth("175px");
        
        Label lblNewLabel = new Label("(Open ID is the the user ID you used to sign in this system. It is either a Goolge ID or an Yahoo ID.)");
        grid.setWidget(0, 2, lblNewLabel);
        
        Label lblFirstName = new Label("First Name");
        grid.setWidget(1, 0, lblFirstName);
        lblFirstName.setWidth("125px");
        
        final TextBox fname_textbox = new TextBox();
        grid.setWidget(1, 1, fname_textbox);
        fname_textbox.setWidth("175px");
        
        Label lblLastName = new Label("Last Name");
        grid.setWidget(2, 0, lblLastName);
        lblLastName.setWidth("126px");
        
        final TextBox lname_textbox = new TextBox();
        grid.setWidget(2, 1, lname_textbox);
        lname_textbox.setWidth("175px");
        
        Label lblPsuIdeg = new Label("Psu ID (e.g., xyz123)");
        grid.setWidget(3, 0, lblPsuIdeg);
        lblPsuIdeg.setWidth("127px");
        
        final TextBox psu_id = new TextBox();
        grid.setWidget(3, 1, psu_id);
        psu_id.setWidth("175px");
        grid.getCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_RIGHT);
        grid.getCellFormatter().setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_RIGHT);
        grid.getCellFormatter().setHorizontalAlignment(2, 0, HasHorizontalAlignment.ALIGN_RIGHT);
        grid.getCellFormatter().setHorizontalAlignment(3, 0, HasHorizontalAlignment.ALIGN_RIGHT);
        
        Label lblNewLabel_1 = new Label("(We need this ID to give you credits/points.)");
        grid.setWidget(3, 2, lblNewLabel_1);
        
        Button save_btn = new Button("Save");
        save_btn.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                User user = new User(open_id.getText(), fname_textbox.getText(), lname_textbox.getText(), psu_id.getText());
                insertUser(user);
            }
        });
        grid.setWidget(4, 1, save_btn);
        grid.getCellFormatter().setHorizontalAlignment(4, 1, HasHorizontalAlignment.ALIGN_RIGHT);
	}
	
	   private void getUserOpenID(){
	        // Initialize the service proxy.
	        if (loginServiceSvc == null) {
	            loginServiceSvc = GWT.create(LoginService.class);
	        }
	        
	        // Set up the callback object.
	        AsyncCallback<String> callback = new AsyncCallback<String>() {
	            public void onFailure(Throwable caught) {
	                caught.printStackTrace();
	                
	            }
	            
	            public void onSuccess(String result) {
	                user_id = result.substring(0, result.indexOf(".NOTACTIVATED"));
//	                Window.alert(user_id);
	                open_id.setText(user_id);
	            }
	        };
	        loginServiceSvc.getUserOpenId(callback);
	    }
	
	private void insertUser(final User u){
		// Initialize the service proxy.
		if (loginServiceSvc == null) {
			loginServiceSvc = GWT.create(LoginService.class);
		}
		
		// Set up the callback object.
		AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() {
			public void onFailure(Throwable caught) {
				caught.printStackTrace();
				
			}
			
			public void onSuccess(Boolean result) {
				if (result){
					storeUserInSession(u);
				}
				else{
					
				}
				
			}
		};
		// Make the call to the stock price service.
		loginServiceSvc.insertUserInDB(u, callback);
	}
	
	private void storeUserInSession(User user){
		// Initialize the service proxy.
		if (loginServiceSvc == null) {
			loginServiceSvc = GWT.create(LoginService.class);
		}
		
		// Set up the callback object.
		AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() {
			public void onFailure(Throwable caught) {
				caught.printStackTrace();
			}
			
			public void onSuccess(Boolean result) {
//				Window.Location.replace("ChooseClass.html");
              Window.Location.replace("./ActivationRequired.html");
				
			}
		};
		// Make the call to the stock price service.
		loginServiceSvc.storeUserInSession(user, callback);
	}

}
